from argparse import Namespace
import os
import unittest

import byteSourceCoder


class ByteSourceCoderTestCase(unittest.TestCase):
    def assert_decoded(self, decoded, expect):
        """
        将解码后文件与原文件比较

        @param decoded: 解码文件
        @param expect: 原文件

        @throws AssertionError: 解码文件!=原文件
        """
        self.assertEqual(
            byteSourceCoder.HuffmanSourceCoder.compare_file(decoded, expect), 0)

    def test_encode_decode(self):
        # 配置日志输出等级
        byteSourceCoder.logging.basicConfig(
            level=byteSourceCoder.logging.DEBUG)

        test_datas = {
            'test-data/2DMS,p0=0.5.csv': 'test-data/input,p0=0.5,len=1MB.dat',
            'test-data/2DMS,p0=0.7.csv': 'test-data/input,p0=0.7,len=1MB.dat',
            'test-data/2DMS,p0=1.csv': 'test-data/input,p0=1,len=1MB.dat',
            'test-data/pmf.byte.p0=0.8.csv': 'test-data/source.p0=0.8.len=64KB.dat',
        }
        for pmf, src in test_datas.items():
            args = Namespace()

            # 先对测试数据进行编码
            args.PMF = pmf
            args.INPUT = src
            args.OUTPUT = 'test-data/encoded.dat'
            byteSourceCoder.encode(args)

            # 再对测试数据进行解码
            args.INPUT = args.OUTPUT
            args.OUTPUT = 'test-data/decoded.dat'
            byteSourceCoder.decode(args)

            # 比较编解码前后数据一致性
            self.assert_decoded(args.OUTPUT, src)
        os.remove('test-data/encoded.dat')
        os.remove('test-data/decoded.dat')


if __name__ == '__main__':
    unittest.main(verbosity=2)
